<template>
  <div class="SeckillSetting">
    <!-- 秒杀配置 -->
    <el-form ref="formRef" :model="form" label-width="auto" :disabled="activityReadonly">
      <h3 class="collpase-title">秒杀配置</h3>
      <el-form-item label="配置类型：" prop="seckillType">
        <el-radio-group v-model="form.seckillType" :disabled="isCurrEdit" @change="handleChangeSeckillType">
          <el-radio :label="1">周期秒杀</el-radio>
          <el-radio :label="2">自定义秒杀</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 周期秒杀配置 -->
      <el-form v-if="form.seckillType == 1" ref="formCycleRef" :model="seckillCycleConfig" :rules="rules"
        label-width="auto">
        <h3 class="collpase-title">基础配置</h3>
        <el-form-item label="秒杀周期：" prop="cycleType">
          <el-radio-group v-model="seckillCycleConfig.cycleType" @change="handleChangeCycleType">
            <el-radio :label="1">每天</el-radio>
            <el-radio :label="2">每周</el-radio>
            <el-radio :label="3">每月</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-form-item prop="cycleDate" label="" label-width="0" v-if="seckillCycleConfig.cycleType === 2">
            <!-- 每周 -->
            <el-select v-model="seckillCycleConfig.cycleDate" multiple class="m-2" placeholder="请选择" style="width: 180px"
              @change="formCycleUpdateData">
              <el-option v-for="item in weekOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="cycleDate" label-width="0" v-if="seckillCycleConfig.cycleType === 3">
            <!-- 每月 -->
            <el-select v-model="seckillCycleConfig.cycleDate" multiple class="m-2" placeholder="请选择" style="width: 180px"
              @change="formCycleUpdateData">
              <el-option v-for="item in calendarOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          &nbsp;&nbsp;
          <el-form-item label-width="0" prop="Date">
            <!-- 每天 -->
            <el-time-picker style="width: 220px" v-model="seckillCycleConfig.Date" is-range range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" value-format="HH:mm:ss" @change="handleChangeCycleDate" />
          </el-form-item>
        </el-form-item>
        <!-- 参与限制 -->
        <h3 class="collpase-title">参与限制</h3>
        <el-form-item label="参与总次数：">
          <el-radio-group v-model="seckillCycleConfig.partTotalLimit">
            <el-radio :label="0">不限</el-radio>
            <el-radio :label="1">限制</el-radio>
          </el-radio-group>
          <template v-if="seckillCycleConfig.partTotalLimit == 1">
            <el-form-item label-width="10px" prop="partTotalNum">
              <el-input v-model="seckillCycleConfig.partTotalNum" placeholder="Please input" v-if="false" />
              <EasyNumberInput v-model="seckillCycleConfig.partTotalNum" :min="1" :max="9999" :precision="0" unit="次" />
            </el-form-item>
          </template>
        </el-form-item>
        <el-form-item label="参与次数：">
          每人&nbsp;&nbsp;
          <el-select v-model="seckillCycleConfig.partLimitType" placeholder="请选择" style="width: 100px">
            <el-option v-for="(item, key) in frequencyType" :key="key" :label="item" :value="Number(key)" />
          </el-select>
          &nbsp;&nbsp;最多
          <el-form-item label-width="10px" prop="partLimitNum">
            <el-input v-model="seckillCycleConfig.partLimitNum" placeholder="Please input" v-if="false" />
            <EasyNumberInput v-model="seckillCycleConfig.partLimitNum" :min="1" :max="9999" unit="次" :precision="0">
            </EasyNumberInput>
          </el-form-item>
        </el-form-item>
        <!-- 商品池 -->
        <h3 class="collpase-title">商品池</h3>
        <PrizePool ref="poolCycleRef" v-model="seckillCycleConfig.prizeAreas" :poolType="[2]"
          :poolBaseInfo="prizePoolType" :pageFlag="form.pageFlag" @change="formCycleUpdateData">
        </PrizePool>
      </el-form>
      <!-- 自定义秒杀配置 -->
      <el-tabs v-else type="border-card" v-model="currentTaskIndex" class="demo-tabs" editable @tab-remove="removeTab"
        @tab-add="addTab">
        <el-tab-pane v-for="(item, index) in seckillCustomConfig" :key="index" :label="item.label" :name="item.label">
          <el-form :ref="(el) => {
            if (el) formCustomRef[index] = el;
          }
            " :model="seckillCustomConfig[index]" :rules="rules" label-width="auto">
            <!-- 基础配置 -->
            <h3 class="collpase-title">基础配置</h3>
            <el-form-item label="区域名称：" prop="name">
              <el-input v-model="item.name" :minlength="0" :maxlength="20" show-word-limit placeholder="请输入区域名称"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="区域时间：" prop="Date">
              <el-date-picker v-model="item.Date" type="datetimerange" :shortcuts="shortcuts" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),]" />
            </el-form-item>
            <!-- 参与限制 -->
            <h3 class="collpase-title">参与限制</h3>
            <el-form-item label="参与总次数：">
              <el-radio-group v-model="item.partTotalLimit" @change="formCustomUpdateData()">
                <el-radio :label="0">不限</el-radio>
                <el-radio :label="1">限制</el-radio>
              </el-radio-group>
              <template v-if="item.partTotalLimit == 1">
                <el-form-item label-width="10px" prop="partTotalNum">
                  <el-input v-model="item.partTotalNum" placeholder="Please input" v-if="false" />
                  <EasyNumberInput v-model="item.partTotalNum" :min="1" :max="9999" :precision="0" unit="次" />
                </el-form-item>
              </template>
            </el-form-item>
            <el-form-item label="参与次数：">
              每人&nbsp;&nbsp;
              <el-select v-model="item.partLimitType" placeholder="请选择" style="width: 100px"
                @change="formCustomUpdateData()">
                <el-option v-for="(item, key) in frequencyType" :key="key" :label="item" :value="Number(key)" />
              </el-select>
              &nbsp;&nbsp;最多
              <el-form-item label-width="10px" prop="partLimitNum">
                <el-input v-model="item.partLimitNum" placeholder="Please input" v-if="false" />
                <EasyNumberInput v-model="item.partLimitNum" :min="1" :max="9999" unit="次" :precision="0">
                </EasyNumberInput>
              </el-form-item>
            </el-form-item>
            <!-- 商品池 -->
            <h3 class="collpase-title">商品池</h3>
            <PrizePool :ref="(el) => {
              if (el) poolCustomRef[index] = el;
            }
              " v-model="item.prizeAreas" :poolType="[2]" :poolBaseInfo="prizePoolType" :pageFlag="form.pageFlag"
              @change="formCustomUpdateData($event, index)"></PrizePool>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script setup>
import PrizePool from "./PrizePool.vue";
import { zoonType } from "../components/config";
import {
  freeType,
  frequencyType,
  weekOptions,
  calendarOptions,
} from "@/config/dictionary";
import { formatTimeStamp, timestampToTime } from "@/utils";
import { ElNotification } from "element-plus";
// props
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

// DATA
const form = ref({
  actId: null,
  seckillType: 1,
});
const rules = ref({
  name: [{ required: true, message: "请输入", trigger: "blur" }],
  Date: [{ required: true, message: "请选择时间", trigger: "blur" }],
  cycleDate: [{ required: true, message: "请选择时间", trigger: "blur" }],
  partTotalNum: [
    { required: true, message: "请选择限制次数", trigger: "blur" },
  ],
  partLimitNum: [
    { required: true, message: "请选择参与次数", trigger: "blur" },
  ],
  prizeAreas: [{ required: true, message: "请上架商品", trigger: "change" }],
});
const formCycleRef = ref();
const poolCycleRef = ref();
const formCustomRef = ref([]);
const poolCustomRef = ref([]);

const isCurrEdit = ref(false);

const activityId = inject("activityId", { value: "" }),
  activityReadonly = inject("activityReadonly", false);
const prizeAreas = ref([]);
// 周期
const seckillCycleConfig = ref({
  seckillId: null,
  actId: null,
  cycleType: 1,
  Date: [],
  cycleDate: "",
  startTime: null,
  endTime: null,
  partTotalLimit: 0,
  partTotalNum: null,
  partLimitType: 1,
  partLimitNum: null,
  prizeAreas: [],
  prizeArea: null,
});
// 自定义
const seckillCustomConfig = ref([
  {
    name: "",
    label: "区域1",
    seckillId: null,
    actId: null,
    cycleType: 1,
    Date: [],
    cycleDate: "",
    startTime: null,
    endTime: null,
    partTotalLimit: 0,
    partTotalNum: null,
    partLimitType: 1,
    partLimitNum: null,
    prizeAreas: [],
    prizeArea: null,
  },
]);
const currentTaskIndex = ref("区域1");
const shortcuts = [
  {
    text: "过去一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "过去一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "过去三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// watch
const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);
// 自定义秒杀类型监听
watch(
  () => form.value.seckillType,
  (val) => {
    if (val === 2) {
      nextTick(() => {
        initPrize();
        formCustomUpdateData();
      });
    }
  },
  {
    immediate: true,
  }
);

// onMounted
onMounted(() => { });

// METHODS
const emits = defineEmits(["change", "update:modelValue"]);
const createPool = (base) => {
  console.log("enter createPool", prizeAreas.value.length);
  let pool = {};
  pool = {
    defaulted: base.defaulted,
    type: base.type,
    subType: base.subType,
    pageFlag: form.value.pageFlag,
    name: `${base.defalut ? "默认" : ""}${base.name}`,
    uid: `${form.value.pageFlag}-pool-${prizeAreas.value.length}`,
    prizeInfos: [],
    viewExpression: "",
    viewOriginal:
      base.viewOriginal && typeof base.viewOriginal === "string"
        ? JSON.parse(base.viewOriginal)
        : base.viewOriginal,
  };

  return pool;
};
const formatData = (value) => {
  let val = JSON.parse(JSON.stringify(value));
  console.log("val formatData", val);
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
  });
  prizeAreas.value = val.prizeAreas || [];
  if (form.value.actId) {
    isCurrEdit.value = true;
  } else {
    isCurrEdit.value = false;
  }
  // 编辑秒杀活动
  if (form.value.actId || val.actSeckillConfig) {
    form.value.seckillType = val.actSeckillConfig.seckillType;
    if (form.value.seckillType === 1) {
      // 获取原数据
      seckillCycleConfig.value = JSON.parse(
        JSON.stringify(val.actSeckillConfig.seckillAreas[0])
      );
      seckillCycleConfig.value.prizeAreas = JSON.parse(
        JSON.stringify(val.prizeAreas)
      );
      // 周期时间处理
      let cycleStartTimeStrVal = seckillCycleConfig.value.startTime.toString();
      let cycleEndTimeStrVal = seckillCycleConfig.value.endTime.toString();
      console.log(
        cycleStartTimeStrVal.length,
        cycleStartTimeStrVal.length,
        "00000"
      );

      // startTime 没有六位 //后面要求要精确到秒
      let dealStartTime = cycleStartTimeStrVal.padStart(6, '0');
      // endTime 没有六位
      let dealEndTime = cycleEndTimeStrVal.padEnd(6, 0);
      // 处理日期
      seckillCycleConfig.value.Date = [];
      seckillCycleConfig.value.Date[0] =
        (dealStartTime + "").slice(0, 2) +
        ":" +
        (dealStartTime + "").slice(2, 4) + ":" + (dealStartTime + "").slice(4, 6);
      seckillCycleConfig.value.Date[1] =
        (dealEndTime + "").slice(0, 2) +
        ":" +
        (dealEndTime + "").slice(2, 4) + ":" + (dealEndTime + "").slice(4, 6);


      // if (cycleStartTimeStrVal.length != 6 || cycleEndTimeStrVal.length != 6) {

      //   // 处理非正常时间
      //   if (
      //     cycleStartTimeStrVal.length != 6 &&
      //     cycleEndTimeStrVal.length === 6
      //   ) {


      //     if (cycleStartTimeStrVal.length == 1) {
      //       dealStartTime = "00000" + seckillCycleConfig.value.startTime;
      //     }
      //     if (cycleStartTimeStrVal.length == 2) {
      //       dealStartTime = "0000" + seckillCycleConfig.value.startTime;
      //     }
      //     if (cycleStartTimeStrVal.length == 3) {
      //       dealStartTime = "000" + seckillCycleConfig.value.startTime;
      //     }
      //     if (cycleStartTimeStrVal.length == 4) {
      //       dealStartTime = "00" + seckillCycleConfig.value.startTime;
      //     }
      //     if (cycleStartTimeStrVal.length == 5) {
      //       dealStartTime = "0" + seckillCycleConfig.value.startTime;
      //     }

      //     seckillCycleConfig.value.Date = [];

      //     seckillCycleConfig.value.Date[0] =
      //       dealStartTime.slice(0, 2) + ":" + dealStartTime.slice(2, 4) + dealStartTime.slice(4);
      //     seckillCycleConfig.value.Date[1] =
      //       (seckillCycleConfig.value.endTime + "").slice(0, 2) +
      //       ":" +
      //       (seckillCycleConfig.value.endTime + "").slice(2, 4);
      //   } else if (
      //     cycleStartTimeStrVal.length >= 4 &&
      //     cycleEndTimeStrVal.length != 6
      //   ) {

      //     if (cycleEndTimeStrVal.length == 1) {
      //       dealEndTime = "000" + seckillCycleConfig.value.endTime;
      //     }
      //     if (cycleEndTimeStrVal.length == 2) {
      //       dealEndTime = "00" + seckillCycleConfig.value.endTime;
      //     }
      //     if (cycleEndTimeStrVal.length == 3) {
      //       dealEndTime = "0" + seckillCycleConfig.value.endTime;
      //     }
      //     seckillCycleConfig.value.Date = [];
      //     seckillCycleConfig.value.Date[0] =
      //       (seckillCycleConfig.value.startTime + "").slice(0, 2) +
      //       ":" +
      //       (seckillCycleConfig.value.startTime + "").slice(2, 4);
      //     seckillCycleConfig.value.Date[1] =
      //       dealEndTime.slice(0, 2) + ":" + dealEndTime.slice(2, 4);
      //   } else if (
      //     cycleStartTimeStrVal.length != 4 &&
      //     cycleEndTimeStrVal.length != 4
      //   ) {
      //     // startTime 没有四位 endTime 没有四位
      //     console.log("enter 3");
      //     // dealStartTime
      //     let dealStartTime = "";
      //     if (cycleStartTimeStrVal.length == 1) {
      //       dealStartTime = "000" + seckillCycleConfig.value.startTime;
      //     }
      //     if (cycleStartTimeStrVal.length == 2) {
      //       dealStartTime = "00" + seckillCycleConfig.value.startTime;
      //     }
      //     if (cycleStartTimeStrVal.length == 3) {
      //       dealStartTime = "0" + seckillCycleConfig.value.startTime;
      //     }
      //     // dealEndTime
      //     let dealEndTime = "";
      //     if (cycleEndTimeStrVal.length == 1) {
      //       dealEndTime = "000" + seckillCycleConfig.value.endTime;
      //     }
      //     if (cycleEndTimeStrVal.length == 2) {
      //       dealEndTime = "00" + seckillCycleConfig.value.endTime;
      //     }
      //     if (cycleEndTimeStrVal.length == 3) {
      //       dealEndTime = "0" + seckillCycleConfig.value.endTime;
      //     }
      //     seckillCycleConfig.value.Date = [];
      //     seckillCycleConfig.value.Date[0] =
      //       dealStartTime.slice(0, 2) + ":" + dealStartTime.slice(2, 4);
      //     seckillCycleConfig.value.Date[1] =
      //       dealEndTime.slice(0, 2) + ":" + dealEndTime.slice(2, 4);
      //   }
      // } else {

      // }
      // 处理每周 每月
      if (seckillCycleConfig.value.cycleType != 1) {
        seckillCycleConfig.value.cycleDate =
          seckillCycleConfig.value.cycleDate.split(",");
      }
      formCycleUpdateData();
    } else {
      console.log("enter sss");
      currentTaskIndex.value = "区域1";
      seckillCustomConfig.value = JSON.parse(
        JSON.stringify(val.actSeckillConfig.seckillAreas)
      );
      // 处理时间段Date
      seckillCustomConfig.value.forEach((item, index) => {
        item.label = `区域${index + 1}`;
        item.Date = [];
        item.Date[0] = timestampToTime(item.startTime);
        item.Date[1] = timestampToTime(item.endTime);
      });
      let prizeAreas = JSON.parse(JSON.stringify(val.prizeAreas));
      seckillCustomConfig.value.forEach((item) => {
        prizeAreas.forEach((value) => {
          if (item.prizeArea === value.id || item.prizeArea === value.uid) {
            item.prizeAreas = [];
            item.prizeAreas.push(value);
          }
        });
      });
      formCustomUpdateData();
    }
  }
  // 初始化秒杀活动
  else {
    if (form.value.seckillType === 1) {
      initPrize();
      formCycleUpdateData();
    } else {
      initPrize();
      formCustomUpdateData();
    }
  }
};

// 初始化奖池
const initPrize = () => {
  // 编辑 自定义秒杀可新增区域和奖池
  if (form.value.actId && form.value.seckillType === 2) {
    seckillCustomConfig.value.forEach((item, index) => {
      if (item.prizeAreas.length === 0) {
        for (let i = 0; i < prizePoolType.value.length; i++) {
          item.prizeAreas.push(
            createPool({
              ...prizePoolType.value[i],
            })
          );
        }
      }
    });
  }
  if (form.value.actId) return false;
  // 新建活动初始化奖池
  if (form.value.seckillType === 1) {
    if (prizeAreas.value.length == 0) {
      for (let i = 0; i < prizePoolType.value.length; i++) {
        seckillCycleConfig.value.prizeAreas.push(
          createPool({
            ...prizePoolType.value[i],
          })
        );
      }
    }
  } else {
    seckillCustomConfig.value.forEach((item, index) => {
      if (item.prizeAreas.length === 0) {
        for (let i = 0; i < prizePoolType.value.length; i++) {
          item.prizeAreas.push(
            createPool({
              ...prizePoolType.value[i],
            })
          );
        }
      }
    });
  }
};
// 周期切换自定义
const handleChangeSeckillType = (val) => {
  if (val === 2) {
    initPrize();
    formCustomUpdateData();
  } else {
    formCycleUpdateData();
  }
};
// 周期秒杀切换
const handleChangeCycleType = (val) => {
  if (val === 2 || val === 3) {
    seckillCycleConfig.value.cycleDate = null;
  }
  formCycleUpdateData();
};

const handleChangeCycleDate = (val) => {
  // console.log(val)
  // if(!val) return false;
  // const timeNum1 = Number(val[0].split(':')[0] + val[0].split(':')[1]);
  // const timeNum2 = Number(val[1].split(':')[0] + val[1].split(':')[1]);
  // seckillCycleConfig.value.startTime = timeNum1;
  // seckillCycleConfig.value.endTime = timeNum2;
  // console.log('seckillCycleConfig.value.startTime', seckillCycleConfig.value.startTime)
  // console.log('seckillCycleConfig.value.endTime', seckillCycleConfig.value.endTime)
  // formCycleUpdateData();
};
const addTab = () => {
  // 新增
  currentTaskIndex.value = `区域${seckillCustomConfig.value.length + 1}`;
  seckillCustomConfig.value.push({
    name: "",
    label: `区域${seckillCustomConfig.value.length + 1}`,
    seckillId: null,
    actId: null,
    cycleType: 1,
    Date: [],
    cycleDate: "",
    startTime: null,
    endTime: null,
    partTotalLimit: 0,
    partTotalNum: null,
    partLimitType: 1,
    partLimitNum: null,
    prizeAreas: [],
    prizeArea: null,
  });
  formCustomUpdateData();
  initPrize();
};
const removeTab = (val) => {
  // 删除tab
  seckillCustomConfig.value.forEach((item, index) => {
    if (val === item.label) {
      seckillCustomConfig.value.splice(index, 1);
      poolCustomRef.value.splice(index, 1);
    }
  });
  currentTaskIndex.value = `区域${seckillCustomConfig.value.length}`;
  seckillCustomConfig.value.forEach((item, index) => {
    item.label = `区域${index + 1}`;
  });
  formCustomUpdateData();
};
const handleFocus = (val, index) => {
  seckillCustomConfig.value[index].startTime = formatTimeStamp(val[0]);
  seckillCustomConfig.value[index].endTime = formatTimeStamp(val[1]);
  console.log(seckillCustomConfig.value, "seckillCustomConfig handleFocus");
  formCustomUpdateData();
};
const handleChangeAreaDate = (val, index) => {
  seckillCustomConfig.value[index].startTime = formatTimeStamp(val[0]);
  seckillCustomConfig.value[index].endTime = formatTimeStamp(val[1]);
  console.log(
    seckillCustomConfig.value,
    "seckillCustomConfig handleChangeAreaDate"
  );
  formCustomUpdateData();
};
// 添加奖池
const addPool = () => {
  poolRef.value.addPool();
};
const formCycleUpdateData = (val) => {
  if (!form.value.actId) {
    prizeAreas.value = [];
    prizeAreas.value = JSON.parse(
      JSON.stringify(seckillCycleConfig.value.prizeAreas)
    );
  }
  console.log("prizeAreas.value", prizeAreas.value);
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    actSeckillConfig: JSON.parse(JSON.stringify(seckillCycleConfig.value)),
  });
  emits("change");
};
const formCustomUpdateData = (val, index) => {
  if (!form.value.actId) {
    prizeAreas.value = [];
    seckillCustomConfig.value.forEach((item) => {
      if (item.prizeAreas) {
        item.prizeAreas.forEach((value) => {
          prizeAreas.value.push(value);
        });
      }
    });
  }

  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    actSeckillConfig: JSON.parse(JSON.stringify(seckillCustomConfig.value)),
  });
  emits("change");
};
// 提交数据
const submit = () => {
  if (form.value.seckillType === 1) {
    return new Promise((resolve, reject) => {
      // formCycleRef 周期秒杀validate
      formCycleRef.value.validate(async (valid, invalidFields) => {
        if (valid) {
          let detail = JSON.parse(JSON.stringify(form.value));
          console.log("seckillCycleConfig", seckillCycleConfig.value);
          try {
            await poolCycleRef.value.check();
          } catch (e) {
            reject(e);
          }
          // 周期秒杀 选择天没触发change事件
          let val = seckillCycleConfig.value.Date;
          seckillCycleConfig.value.startTime = Number(
            val[0].split(":")[0] + val[0].split(":")[1] + val[0].split(":")[2]
          );
          seckillCycleConfig.value.endTime = Number(
            val[1].split(":")[0] + val[1].split(":")[1] + val[1].split(":")[2]
          );
          // 检查周期秒杀单日库存限制
          seckillCycleConfig.value.prizeAreas[0].prizeInfos.forEach(
            (item, index) => {
              if (item.childPrizes) {
                item.childPrizes.forEach((value) => {
                  if (value.dayStockLimited != 1) {
                    reject(
                      `请检查礼品包（${value.goodsName || value.name}）商品是否设置单日库存限制`
                    );
                  }
                });
              } else {
                if (item.dayStockLimited != 1) {
                  reject(`请检查（${item.goodsName || item.name}）商品是否设置单日库存限制`);
                }
              }
            }
          );
          // 周期不是每天 需要处理cycleDate
          let cycleDateValue = "";
          if (seckillCycleConfig.value.cycleType != 1) {
            console.log("seckillCycleConfig++++++", seckillCycleConfig.value);
            cycleDateValue = seckillCycleConfig.value.cycleDate.join(",");
          } else {
            seckillCycleConfig.value.cycleDate = "";
          }

          // 处理数据
          let actSeckillConfig = {
            ...form.value,
            seckillAreas: [],
          };
          actSeckillConfig.seckillAreas.push(
            JSON.parse(JSON.stringify(seckillCycleConfig.value))
          );
          // 添加uid
          prizeAreas.value.forEach((item, index) => {
            item.uid = `${form.value.pageFlag}-pool-${index}`;
          });
          actSeckillConfig.seckillAreas[0].prizeAreaUid =
            prizeAreas.value[0].uid;
          // 处理cycleDate
          actSeckillConfig.seckillAreas[0].cycleDate = cycleDateValue;
          // 编辑时id确认
          if (form.value.actId) {
            actSeckillConfig.id = actSeckillConfig.seckillAreas[0].seckillId;
          }
          resolve({
            pageArea: detail,
            prizeAreas: prizeAreas.value,
            actSeckillConfig,
          });
        } else {
          formCycleRef.value.scrollToField(Object.keys(invalidFields)[0]);
          reject("请检查基础信息配置");
        }
      });
    });
  } else {
    const promiseArr = [];
    const errArr = [];
    for (let i = 0; i < formCustomRef.value.length; i++) {
      let promise = new Promise((resolve, reject) => {
        formCustomRef.value[i].validate(async (valid, invalidFields) => {
          if (valid) {
            resolve();
          } else {
            setTimeout(() => {
              ElNotification({
                message: `请检查区域${i + 1}基础信息配置`,
                type: "error",
              });
            }, i * 100);
            errArr.push(i + 1);
            reject();
          }
        });
      });
      promiseArr.push(promise);
    }
    for (let i = 0; i < poolCustomRef.value.length; i++) {
      let promise = poolCustomRef.value[i].check();
      console.log(promise, "promise");
      promise
        .then((val) => { })
        .catch((err) => {
          setTimeout(() => {
            ElNotification({
              message: `秒杀配置区域${i + 1}商品池至少需要添加一个上架商品`,
              type: "error",
            });
          }, i * 10);
        });
      promiseArr.push(promise);
    }
    return Promise.all(promiseArr)
      .then((val) => {
        let detail = JSON.parse(JSON.stringify(form.value));
        // 处理时间
        let timeArr = [];
        seckillCustomConfig.value.forEach((item) => {
          item.startTime = formatTimeStamp(item.Date[0]);
          item.endTime = formatTimeStamp(item.Date[1]);
          timeArr.push(item.startTime);
        });

        // 判断每个区域开始时间是否相等
        // if(timeArr.length != [...new Set(timeArr)].length) {
        //   ElNotification({
        //     message: `基础配置秒杀起始时间不能重复！`,
        //     type: 'error',
        //   });
        //   return false;
        // }

        // 处理数据格式
        let actSeckillConfig = {
          ...form.value,
          seckillAreas: [],
        };
        actSeckillConfig.seckillAreas = JSON.parse(
          JSON.stringify(seckillCustomConfig.value)
        );

        // 置空 prizeAreas.value
        prizeAreas.value = [];
        seckillCustomConfig.value.forEach((item) => {
          item.prizeAreas.forEach((value) => {
            prizeAreas.value.push(value);
          });
        });
        prizeAreas.value.forEach((item, index) => {
          item.uid = `${form.value.pageFlag}-pool-${index}`;
        });
        actSeckillConfig.seckillAreas.forEach((item, index) => {
          prizeAreas.value.forEach((value, key) => {
            if (index === key) {
              item.prizeAreaUid = value.uid;
            }
          });
        });
        // 编辑时id确认
        if (form.value.actId) {
          actSeckillConfig.id = actSeckillConfig.seckillAreas[0].seckillId;
        } else {
          // 新增和复制时没有 actId prizeArea置为null
          actSeckillConfig.seckillAreas.forEach((item) => {
            item.prizeArea = null;
          });
        }
        return {
          pageArea: detail,
          prizeAreas: prizeAreas.value,
          actSeckillConfig,
        };
      })
      .catch((err) => {
        return false;
      });
  }
};

// computed
const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

// defineExpose
defineExpose({ submit, refresh: formatData });
</script>

<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;

  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }

  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

:deep(.el-form-item__label-wrap) {
  margin-left: 11px;
}

:deep(.el-tabs__new-tab) {
  margin: 7px 10px 0 10px;
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
